//
//  View+ReadSize.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/7.
//

import SwiftUI

extension View {
  func ht_readSize(onChange: @escaping (CGSize) -> Void) -> some View {
    background(
      GeometryReader { geometryProxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: geometryProxy.size)
      }
    )
    .onPreferenceChange(SizePreferenceKey.self, perform: onChange)
  }

  func ht_frame(perform: @escaping (CGRect) -> Void) -> some View {
    background(
      GeometryReader {
        Color.clear
          .preference(key: FramePreferenceKey.self, value: $0.frame(in: .global))
      }
    )
    .onPreferenceChange(FramePreferenceKey.self, perform: perform)
  }
}

public struct FramePreferenceKey: PreferenceKey {
  public static var defaultValue: CGRect = .zero
  public static func reduce(value: inout CGRect, nextValue: () -> CGRect) {}
}

private struct SizePreferenceKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}
